<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="../bootstrap/css/bootstrap.min.css">
  <link rel="stylesheet" href="../css/userInfo.css">

  <script src="../bootstrap/js/jquery.min.js"></script>
  <script src="../bootstrap/js/bootstrap.min.js"></script>
  <script src="../js/vue.js"></script>
  <script src="../js/axios.min.js"></script>
  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
  <script src="../js/element-ui.js"></script>
</head>
<title>用户管理</title>
<body style="background-color: #f4f9fa">
<div id="ulInfo">
  <!-- 导航 -->
  <nav class="navbar navbar-expand-md bg-white navbar-light fixed-top" style="font-size: 16px;">
    <h1 class="title">
      <a class="navbar-brand" href="#">
        <img src="../img/studyLogo.png" alt="logo" width="40" height="40">
      </a>
    </h1>
    <!-- 折叠按钮 -->
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbar">
      <ul class="navbar-nav mr-auto">
        <li class="nav-item"><a class="nav-link" href="../main.html">首页</a></li>
        <!--<li class="nav-item"><a class="nav-link" href="collect.html">收藏</a></li>-->
        <li v-if="(currentUser.roleId == 2 || currentUser.roleId == 0)" class="nav-item"><a class="nav-link"
                                                                                            href="videoUpload.html">上传视频</a>
        </li>
        <li v-if="(currentUser.roleId == 2 || currentUser.roleId == 0)" class="nav-item"><a class="nav-link"
                                                                                            href="videoManager.html">视频管理</a>
        </li>
        <li v-if="currentUser.roleId == 0" class="nav-item"><a class="nav-link" href="userManager.html">用户管理</a>
        </li>
        <li v-if="currentUser.roleId == 0" class="nav-item"><a class="nav-link" href="functionManager.html">权限管理</a>
        </li>
        <!--下拉-->
        <li class="dropdown" style="margin-right: 450px">
          <a class="dropdown-toggle nav-link" data-toggle="dropdown" role="button" aria-haspopup="true"
             aria-expanded="false" style="cursor:pointer;">我的 <span class="caret"></span></a>
          <ul class="dropdown-menu" style="text-align: center;">
            <li><a style="color: #6c757d;" href="userInfo.html">个人中心</a></li>
            <li><a style="color: #6c757d;" href="collect.html">我的收藏</a></li>
            <li><a style="color: #6c757d;" href="browse.html">浏览记录</a></li>
            <li><a style="color: #6c757d;" href="../userExit">退出登录</a></li>
          </ul>
        </li>

        <template v-if="currentUser.account == null">
          <li class="nav-item"><a class="nav-link" href="../login.html">你好,请登录</a></li>
          <li class="nav-item"><a class="nav-link" href="#">|</a></li>
          <li class="nav-item"><a class="nav-link" href="../register.html">免费注册</a></li>
        </template>
        <template v-if="currentUser.account != null">
          <li class="nav-item"><a class="nav-link" href="userInfo.html">欢迎你：{{currentUser.account}}</a></li>
          <li class="nav-item"><a class="nav-link" href="#">|</a></li>
          <li class="nav-item"><a class="nav-link" href="../userExit">退出</a></li>
        </template>
      </ul>
      <form id="formSearch" action="" class="form-inline ml-auto">
        <input id="searchInput" type="text" v-model="keyword" class="form-control mr-sm-2" placeholder="Search"
               @change="searchVideo">
        <input @click="searchVideo" type="button" class="btn btn-outline-secondary  my-2 my-sm-0" value="搜索">
      </form>
    </div>
  </nav>
  <div class="all" style="margin-top: 100px">

    <h2 style="text-align: center;margin-top: 30px;margin-bottom: 30px">用户管理</h2>
    <form action="" id="searchForm" name="searchForm" method="post"
          style="width: 80%;margin-left: 20%">
      <label>
        <input v-model="account" type="text" name="account" id="account" list="accountList" placeholder="账号"
               value="" @input="searchAccount">
      </label>
      <datalist id="accountList">
        <template v-for="info in dataArray">
          <option id="option" :value="info">{{info}}</option>
        </template>
      </datalist>
      <label>
        <input v-model="name" type="text" name="name" id="name" list="accountList" placeholder="用户名"
               value="">
      </label>
      <label>
        <input v-model="sex" type="text" name="sex" placeholder="性别" value="">
      </label>
      <input type="button" @Click="getAllUser" value="查询">
      <input type="reset" @Click="() => {this.sex = '';this.name = '';this.account = '';}" value="重置">
    </form>
    <span style="margin-left: 60px;color: #a8b5b5;">提示: 双击单元格可编辑信息</span>
    <table class="table" id="table" style="margin: 10px auto;width: 90%;font-size: 18px; font-family: '微软雅黑';">
      <tr>
        <th>账号</th>
        <th>头像</th>
        <th>姓名</th>
        <th>性别</th>
        <th>生日</th>
        <th>地址</th>
        <th>账号类型</th>
      </tr>
      <template v-for="user in userList.data">
        <tr :userId="user.uid" class="hover">
          <td style="width: 15%">{{user.account}}</td>
          <td style="width: 10%;cursor:pointer;" name="editInfo1" editType="headPicUrl1">
            <img onclick="editHeadPic(this.parentElement)" id="headpic" name="headpic"
                 :src="'../upload/'+user.userDetail.headPicUrl" width="25px" height="25px" alt="头像">
          </td>
          <td ondblclick="edit(this)" editType="name" style="width: 15%;cursor:pointer;" name="editInfo">
            {{user.userDetail.name}}
          </td>
          <td ondblclick="edit(this)" editType="sex" style="width: 10%;cursor:pointer;" name="editInfo">
            {{user.userDetail.sex}}
          </td>
          <td ondblclick="edit(this)" editType="birthday" style="width: 15%;cursor:pointer;" name="editInfo">
            {{user.userDetail.birthday | formatDate}}
          </td>
          <td ondblclick="edit(this)" style="width: 25%;cursor:pointer;" name="editInfo" editType="address">
            {{user.userDetail.address}}
          </td>
          <td :roleId="user.roleId" style="width: 10%;cursor:pointer;" name="editInfo" editType="role">
            <select v-if="user.roleId == 0" :id="user.uid" @Change="editRole(user.uid, user.roleId)">
              <option value="0" selected>管理员</option>
              <option value="1">学生</option>
              <option value="2">老师</option>
              <option value="3">VIP</option>
              <option value="4">禁用</option>
            </select>
            <select v-if="user.roleId == 1" :id="user.uid" @Change="editRole(user.uid, user.roleId)">
              <option value="0">管理员</option>
              <option value="1" selected>学生</option>
              <option value="2">老师</option>
              <option value="3">VIP</option>
              <option value="4">禁用</option>
            </select>
            <select v-if="user.roleId == 2" :id="user.uid" @Change="editRole(user.uid, user.roleId)">
              <option value="0">管理员</option>
              <option value="1">学生</option>
              <option value="2" selected>老师</option>
              <option value="3">VIP</option>
              <option value="4">禁用</option>
            </select>
            <select v-if="user.roleId == 3" :id="user.uid" @Change="editRole(user.uid, user.roleId)">
              <option value="0">管理员</option>
              <option value="1">学生</option>
              <option value="2">老师</option>
              <option value="3" selected>VIP</option>
              <option value="4">禁用</option>
            </select>
            <select v-if="user.roleId == 4" :id="user.uid" @Change="editRole(user.uid, user.roleId)">
              <option value="0">管理员</option>
              <option value="1">学生</option>
              <option value="2">老师</option>
              <option value="3">VIP</option>
              <option value="4" selected>禁用</option>
            </select>
          </td>
        </tr>
      </template>
    </table>
    <div style="width:60%;margin-left:20%; margin-bottom: 50px;text-align:center;" class="centerdiv">
      <input type="button" value="首  页" class="btnPage" @Click="pageOper('min')" style="margin-left: 20%"/>
      <input type="button" value="上一页" class="btnPage" @Click="pageOper('up')"/>
      第<input type="text" v-model="pageNo" class="btn"
              style="width: 34px;text-align: center;margin-bottom: 4px" @blur="pageOper">页&nbsp;&nbsp;<b>·</b>&nbsp;&nbsp;共
      &nbsp;<span v-text="maxPage"></span>&nbsp; 页
      <input type="button" value="下一页" class="btnPage" @Click="pageOper('down')"/>
      <input type="button" value="尾  页" class="btnPage" @Click="pageOper('max')"/>
    </div>
  </div>

</div>
</body>
<script src="../js/diqu2.js"></script>
<script type="text/javascript">
  let message = null;
  /*用户信息*/
  new Vue({
    el: "#ulInfo",
    data() {
      return {
        currentUser: "",
        userList: "",
        dataArray: [],
        account: "",
        name: "",
        sex: "",
        pageNo: "0",
        maxPage: "0",
        keyword: "",
      }
    },
    methods: {
      searchVideo: function () {
        window.location.href = "search.html?keyword=" + this.keyword;
      },
      //获取当前用户
      getCurrentUser: function () {
        const loading = this.$loading({
          lock: true,
          text: 'Loading...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        axios.get("../getCurrentUser")
          .then(result => {
            loading.close();
            this.currentUser = result.data;
          })
          .catch(function (error) {
            loading.close();
            message.error(error.response.data);
            if (error.response.status === 401) window.location.href = "../login.html";
          })
      },
      //获取所有用户
      getAllUser: function () {
        const loading = this.$loading({
          lock: true,
          text: 'Loading...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        axios.get("../getAllUser?account=" + this.account + "&name=" + this.name + "&sex=" + this.sex + "&pageNo=1")
          .then(result => {
            loading.close();
            this.userList = result.data;
            this.pageNo = this.userList.pageNo;
            this.maxPage = this.userList.maxPageNo;
          })
          .catch(function (error) {
            loading.close();
            message.error(error.response.data);
            if (error.response.status === 401) window.location.href = "../login.html";
          })
      },
      //翻页操作
      pageOper: function (type) {
        let newPage = this.pageNo;
        if (type === "min") {
          newPage = 1
        } else if (type === "up") {
          newPage = newPage - 1;
          if (newPage < 1) {
            newPage = 1;
          }
        } else if (type === "down") {
          newPage = newPage + 1;
          if (newPage > this.maxPage) {
            newPage = this.maxPage;
          }
        } else if (type === "max") {
          newPage = this.maxPage;
        }
        const loading = this.$loading({
          lock: true,
          text: 'Loading...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        axios.get("../getAllUser?account=" + this.account + "&name=" + this.name + "&sex=" + this.sex + "&pageNo=" + newPage)
          .then(result => {
            loading.close();
            this.userList = result.data;
            this.pageNo = this.userList.pageNo;
            this.maxPage = this.userList.maxPageNo;
          })
          .catch(function (error) {
            loading.close();
            message.error(error.response.data);
            if (error.response.status === 401) window.location.href = "../login.html";
          })
      },

      //根据字段名搜索
      searchAccount: function () {
        let keyword = this.account;
        if (keyword === "") {
          return;
        }

        const loading = this.$loading({
          lock: true,
          text: 'Loading...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        axios
          .get('../queryUserInfoColumnByKeyword?column=account&keyword=' + keyword)
          .then(result => {
            loading.close();
            this.dataArray = eval(result.data)
          })
          .catch(function (error) {
            loading.close();
            message.error(error.response.data);
            if (error.response.status === 401) window.location.href = "../login.html";
          });
      },
      //修改用户角色
      editRole: function (id, oldRoleId) {
        let selectRole = document.getElementById(id);
        let roleId = selectRole.options[selectRole.selectedIndex].value;
        if (roleId == "0" || oldRoleId == "0") {
          alert("管理员角色禁止前台修改")
          location.reload()
          return
        }
        axios.get("../updateUser?uid=" + id + "&roleId=" + roleId).then(result => {
          message.success("更新成功")
        }).catch(function (error) {
          message.error(error.response.data);
          if (error.response.status === 401) window.location.href = "../login.html";
        })
      },
    },
    mounted() {
      message = this.$message;
      this.getCurrentUser();
      this.getAllUser();
    },
    filters: {
      formatDate(time) {
        var date = new Date(time);
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var date = date.getDate();
        return year + "-" + month + "-" + date
      },
      //格式化角色类型
      formatRole(roleId) {
        if (roleId === 0) {
          return "管理员";
        } else if (roleId === 1) {
          return "学生";
        } else if (roleId === 2) {
          return "老师";
        } else if (roleId === 3) {
          return "VIP学生";
        } else if (roleId === 4) {
          return "账号禁用";
        }
        return "未知"
      },
    }
  });

  //修改头像
  function editHeadPic() {
    let td = $("#headpic").parent();
    //获取用户的id
    let userId = td.parentNode.getAttribute("userId");
    td.append("<input type='file' id='EditHeadPic' name='EditHeadPic' style='display: none'>");

    let EditHeadPic = $("#EditHeadPic");
    EditHeadPic.click();
    //为图片选择框绑定change事件
    EditHeadPic.change(function () {
      let reader = new FileReader();
      reader.onloadend = function (e) {
        //修改图片的src属性，显示新的图片
        document.getElementById('headpic').src = e.target.result;
      }
      reader.readAsDataURL(this.files[0]);  // 读取文件内容
      let formData = new FormData();
      formData.append('EditHeadPic', this.files[0]);

      $.ajax({
        url: "../userInfoUpdate?uid=" + userId + "&editType=headPicUrl",
        type: "POST",
        data: formData,
        cache: false,
        processData: false,
        contentType: false,
      });
    });
  }

  //编辑信息
  function edit(td) {
    //获取旧文本
    let old = td.innerText;
    //获取修改的类型
    let type = td.getAttribute('editType');
    //获取用户的id
    userId = td.parentNode.getAttribute("userId");
    if (type === "birthday") {
      td.innerHTML = "<input type='date' size='20' style='width:100%;'>";
    } else if (type === "sex") {
      td.innerHTML =
        "<input type='radio' name='sex' value='男'>&nbsp;男&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
        "<input type='radio' name='sex' value='女'>&nbsp;女&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
        "<input type='radio' name='sex' value='保密'>&nbsp;保密&nbsp;&nbsp;&nbsp;&nbsp;";

      //设置选中
      $(":radio[name='sex'][value='" + old + "']").prop("checked", "checked");
      let interval = setInterval(setSex, 1000);

      function setSex() {
        let radio = $("input[type='radio']:checked");
        let newText = radio.val();

        if (newText !== old && (newText === "男" || newText === "女" || newText === "保密")) {
          clearInterval(interval);

          axios.get("../userInfoUpdate?uid=" + userId + "&editType=sex&newText=" + newText)
            .then(result => {
              td.innerHTML = newText;
              message.success("更新成功")
            }).catch(function (error) {
            td.innerText = old;
            message.error(error.response.data);
            if (error.response.status === 401) window.location.href = "../login.html";
          })
        }
      }

      return;
    } else if (type === "address") {
      //地区选择
      td.innerHTML = "<select name='sheng'></select>  <select name='shi'></select>  <select name='qu'></select>";
      let select = new PCAS("sheng", "shi", "qu", "", "", "");

      let interval = setInterval(setText, 1000);

      function setText() {
        let sheng = select.SelP.options[select.SelP.selectedIndex].value;
        let shi = select.SelC.options[select.SelC.selectedIndex].value;
        let qu = select.SelA.options[select.SelA.selectedIndex].value;
        let newText = sheng + shi + qu;
        if (qu !== "--请选择地区--" && qu !== "" && shi !== "--请选择地区--") {
          clearInterval(interval);

          axios.get("../userInfoUpdate?uid=" + userId + "&editType=address&newText=" + newText)
            .then(result => {
              td.innerHTML = newText;
              message.success("更新成功")
            }).catch(function (error) {
            td.innerText = old;
            message.error(error.response.data);
            if (error.response.status === 401) window.location.href = "../login.html";
          })
        }
      }

      return;
    } else {
      //修改其他
      td.innerHTML = "<input type='text' size='20' style='width:80%;'>";
    }
    let input = td.firstChild;

    input.value = old;
    input.select();
    //绑定输入框失去焦点事件,更新
    input.onblur = function () {
      update(this, old, type);
    }
  }

  /**
   * 失去焦点，更新
   */
  function update(input, old, type) {
    let newText = input.value;
    //input的父节点是td
    let TD = input.parentNode;

    if (!newText) {
      message.error('您的输入为空，修改失败！');
      TD.innerText = old;
      return;
    }


    axios.get("../userInfoUpdate?uid=" + userId + "&editType=" + type + "&newText=" + newText)
      .then(result => {
        TD.innerText = newText;
        if (newText != old) {
          message.success("更新成功")
        }
      }).catch(function (error) {
      TD.innerText = old;
      message.error(error.response.data);
      if (error.response.status === 401) window.location.href = "../login.html";
    })
  }
</script>
</html>
